package cn.leedsoft.luma.plugins.shiro;

import cn.leedsoft.luma.mapper.domain.User;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * Created by leeds on 2016/7/7 22:25.
 */
public class PasswordHelper {

    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();;
    private String algorithmName = "md5";
    private int hashIterations = 2;//散列迭代次数md5(md5(密码+salt))

    public void encryptPassword(User user) {

        user.setSalt(randomNumberGenerator.nextBytes().toHex());//生成salt

        String newPassword = getPassword(user.getPassword(), user.getSalt());//生成加密后的密码

        user.setPassword(newPassword);
    }

    public String getPassword(String password,String salt){
        return new SimpleHash(
                algorithmName,
                password,
                salt,//看源码，其实已经执行了ByteSource.Util.bytes()
                hashIterations).toHex();//散列完成之后的二进制流，转为Hex编码
    }
}
